package com.latefly.skewwork.utils

import android.Manifest
import android.content.Context
import android.content.pm.PackageManager
import android.os.Environment
import androidx.core.content.ContextCompat
import java.io.BufferedReader
import java.io.BufferedWriter
import java.io.File
import java.io.FileInputStream
import java.io.FileNotFoundException
import java.io.FileOutputStream
import java.io.IOException
import java.io.InputStreamReader
import java.io.OutputStreamWriter

object FileUtils {

    private const val IMAGE_PREFIX = "Image_"
    private const val JPG_SUFFIX = ".jpg"
    private const val FOLDER_NAME = "Photo"

    fun createDirectoryIfNotExist(context: Context) {
        val folder = File(
            context.getExternalFilesDir(Environment.DIRECTORY_PICTURES)?.absolutePath +
                    File.separator + FOLDER_NAME
        )
        if (!folder.exists()) {
            folder.mkdirs()
        }
    }

    fun createFile(context: Context) = File(
        context.getExternalFilesDir(Environment.DIRECTORY_PICTURES)?.absolutePath +
                File.separator + FOLDER_NAME + File.separator + IMAGE_PREFIX + System.currentTimeMillis() + JPG_SUFFIX
    )

    fun readFileFromInternalStorage(context: Context, fileName: String): String? {
        val inputFile = context.getFileStreamPath(fileName)

        return try {
            FileInputStream(inputFile).use { inputStream ->
                val reader = BufferedReader(InputStreamReader(inputStream))
                val sb = StringBuilder()

                reader.forEachLine { line ->
                    sb.append(line)
                    sb.append("\n")
                }
                reader.close()
                sb.toString()
            }
        } catch (e: FileNotFoundException) {
            e.printStackTrace()
            null
        } catch (e: IOException) {
            e.printStackTrace()
            null
        }
    }

    fun writeStringInternalStorage(context: Context, fileName: String, content: String) {
        val outputFile = context.getFileStreamPath(fileName)

        try {
            FileOutputStream(outputFile).use { outputStream ->
                val writer = BufferedWriter(OutputStreamWriter(outputStream))
                writer.write(content)
                writer.flush()
                writer.close()
            }
        } catch (e: FileNotFoundException) {
            e.printStackTrace()
        } catch (e: IOException) {
            e.printStackTrace()
        }
    }

//    fun readFromPublicDirectory(context: Context, dirType: String, fileName: String): String? {
//        val directory = Environment.getExternalStoragePublicDirectory(dirType)
//        val file = File(directory, fileName)
//
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && !hasWritePermission(context)) {
//            // 请求权限
//            ActivityCompat.requestPermissions(
//                (context as Activity),
//                arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE),
//                1
//            )
//            // 在onRequestPermissionsResult回调中处理权限结果
//            // 此处假设已获得权限并继续操作
//        }
//
//        val inputFile = context.getFileStreamPath(fileName)
//        return try {
//            FileInputStream(inputFile).use { inputStream ->
//                val reader = BufferedReader(InputStreamReader(inputStream))
//                val sb = StringBuilder()
//
//                reader.forEachLine { line ->
//                    sb.append(line)
//                    sb.append("\n")
//                }
//                reader.close()
//                sb.toString()
//            }
//        } catch (e: FileNotFoundException) {
//            e.printStackTrace()
//            null
//        } catch (e: IOException) {
//            e.printStackTrace()
//            null
//        }
//    }
//
//    fun writeToPublicDirectory(
//        context: Context,
//        dirType: String,
//        fileName: String,
//        content: String
//    ) {
//        val directory = Environment.getExternalStoragePublicDirectory(dirType)
//        val file = File(directory, fileName)
//
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && !hasWritePermission(context)) {
//            // 请求权限
//            ActivityCompat.requestPermissions(
//                (context as Activity),
//                arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE),
//                1
//            )
//        }
//        val outputFile = context.getFileStreamPath(fileName)
//        try {
//            FileOutputStream(outputFile).use { outputStream ->
//                val writer = BufferedWriter(OutputStreamWriter(outputStream))
//                writer.write(content)
//                writer.flush()
//                writer.close()
//            }
//        } catch (e: FileNotFoundException) {
//            e.printStackTrace()
//        } catch (e: IOException) {
//            e.printStackTrace()
//        }
//    }

    // 检查是否已有权限
    private fun hasWritePermission(context: Context): Boolean {
        return ContextCompat.checkSelfPermission(
            context,
            Manifest.permission.WRITE_EXTERNAL_STORAGE
        ) == PackageManager.PERMISSION_GRANTED
    }


}